package com.qiku.dao.impl;

import com.qiku.dao.CollectDao;
import com.qiku.pojo.Collect;
import com.qiku.utils.DateUtils;
import com.qiku.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class CollectDaoImpl implements CollectDao {
    private QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    /**
     * 根据用户id 查询 表collect
     * 操作对象 中间表 collect 主要获取 resource_id
     *
     * @param userId
     * @return
     */
    @Override
    public List<Collect> findCollectByUserId(int userId) {
        try {
            String sql = "select * from collect where user_id = ?";
//            因为一个用户id 可能对应多个collect对象
            List<Collect> collectList = qr.query(sql, new BeanListHandler<>(Collect.class), userId);
            return collectList;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int addCollect(Collect collect) {
        try {
            String s = "insert into collect (id , user_id , resource_id , collect_date) values (null,?,?,?)";
            int i = qr.update(s, collect.getUser_id(), collect.getResource_id(), DateUtils.getDateFormart());
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int subCollect(int c_id) {
        String sql = "DELETE FROM collect where id = ?";
        try {
            int i = qr.update(sql, c_id);
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    //根据用户id和资源id查询收藏表项
    public Integer findCollectById(int u_id, String r_id) {
        try {
            String sql = "select id from collect where user_id = ? and resource_id = ?";
            Object query = qr.query(sql, new ScalarHandler<>(), u_id, r_id);
            if (query != null) {
                Integer i = (Integer) query;
                return i;
            } else {
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

}
